package com.farewell.hotel.controller;

import com.farewell.hotel.entity.InfoSearch;
import com.farewell.hotel.pojo.InRoomInfo;
import com.farewell.hotel.service.InRoomInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author Farewell
 * @date 2021/4/22
 */
@Controller
public class InRoomController {
    @Autowired
    private InRoomInfoService inRoomInfoService;

    @RequestMapping("deleteInRoomInfo.do")
    public String deleteInRoomInfo(@RequestParam("id") Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            inRoomInfoService.deleteInRoomInfo(id);
            response.sendRedirect(request.getContextPath() + "/getInRoomInfo.do");
        } catch (IOException e) {
            e.printStackTrace();
            return "删除入住信息失败";
        }
        return null;
    }

    /**
     * 入住信息添加
     *
     * @param inRoomInfo 入住信息条件
     * @return true or false
     */
    @RequestMapping("addInRoomInfo.do")
    public String addInRoomInfo(InRoomInfo inRoomInfo, HttpServletResponse response, HttpServletRequest request) {
        try {
            inRoomInfoService.addInRoomInfo(inRoomInfo);
            String url = request.getContextPath() + "/getInRoomInfo.do";
            response.sendRedirect(url);
        } catch (Exception e) {
            e.printStackTrace();
            return "添加入住信息失败";
        }
        return null;
    }

    /**
     * 查询入住信息
     *
     * @param inRoomInfoSearch 入住查询条件
     * @param httpSession      全局缓存
     * @param pageNum          起始页
     * @return index.jsp
     */
    @RequestMapping(value = "getInRoomInfo.do")
    public String getInRoomInfo(InfoSearch inRoomInfoSearch, HttpSession httpSession, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
        if (inRoomInfoSearch.getConditionType() == null || inRoomInfoSearch.getKeyword() == null) {
            inRoomInfoSearch = null;
        }
        // 分页查询所有信息
        PageHelper.startPage(pageNum, 10);
        List<InRoomInfo> inRoomInfoList = inRoomInfoService.findInRoomInfo(inRoomInfoSearch);
        PageInfo<InRoomInfo> pageInfo = new PageInfo<>(inRoomInfoList);
        httpSession.setAttribute("pageInfo", pageInfo);
        System.out.println(inRoomInfoList);
        return "bill/inroominfo.jsp";
    }
}
